var express = require('express');
var router = express.Router();
const UsersApi = require('../api/users.js');
const { md5 } = require("tools-factory-tang/salt");
const { createToken } = require("tools-factory-tang/jwt");
// const users = [
//   { id: 0, username: "zhangsan", password: "111111" },
//   { id: 1, username: "lisi", password: "222222" }
// ]

// 登录  GET 方法
router.get('/login', async function (req, res, next) {
  // GET 类型的请求需要通过 req.query 来获取参数
  let { username, password } = req.query;
  password = md5(password);
  const data = await UsersApi.login({ username, password });
  const result = {
    status: false,
  };
  console.log(data);
  if (data.length === 1) {
    const token = createToken({
      username,
    });
    result.status = true;
    result.token = token;
  }
  res.send(result);
});

// POST 方法
// router.post("/login", function (req, res, next) {
//   // POST 类型的请求需要通过 req.body 来获取参数
//   const { username, password } = req.body;
//   res.send("LOGIN POST");
// });
// 注册
router.post('/reg', async function (req, res, next) {
  let { username, password } = req.body;
  password = md5(password);
  const data = await UsersApi.reg({ username, password });
  res.send(data);
});
module.exports = router;
